#!/bin/bash

# 服务器信息
SERVER_HOST="192.168.10.74"
SERVER_USER="pyapp"
REMOTE_BASE_DIR="/home/pyapp"
SSH_KEY="$HOME/.ssh/cardsys_test_deploy"
SSH_OPTS="-i $SSH_KEY -o StrictHostKeyChecking=accept-new"

# 错误处理函数
handle_error() {
    echo "错误：$1"
    exit 1
}

# 确保 SSH 密钥存在
if [ ! -f "$SSH_KEY" ]; then
    handle_error "SSH 密钥文件不存在：$SSH_KEY"
fi

# 测试 SSH 连接
echo "测试 SSH 连接..."
ssh $SSH_OPTS ${SERVER_USER}@${SERVER_HOST} "echo '连接成功'" || handle_error "SSH 连接失败"

# 确保本地打包文件存在
if [ ! -d "dist" ]; then
    handle_error "dist 目录不存在，请先运行 package.sh"
fi

# 获取最新的打包文件
FRONTEND_PACKAGE=$(ls -t dist/frontend_*.tar.gz | head -n1)
BACKEND_PACKAGE=$(ls -t dist/backend_*.tar.gz | head -n1)

if [ -z "$FRONTEND_PACKAGE" ] || [ -z "$BACKEND_PACKAGE" ]; then
    handle_error "未找到打包文件，请先运行 package.sh"
fi

echo "=== 开始部署 ==="
echo "使用以下文件："
echo "- 前端：$(basename $FRONTEND_PACKAGE)"
echo "- 后端：$(basename $BACKEND_PACKAGE)"

# 创建远程目录结构
echo "创建远程目录..."
ssh $SSH_OPTS ${SERVER_USER}@${SERVER_HOST} "mkdir -p ${REMOTE_BASE_DIR}/{workspace/cardsysTest/{backend,logs},www/cardsys_test}" || handle_error "创建远程目录失败"

# 上传文件
echo "上传文件..."
scp $SSH_OPTS $FRONTEND_PACKAGE ${SERVER_USER}@${SERVER_HOST}:${REMOTE_BASE_DIR}/frontend.tar.gz || handle_error "上传前端文件失败"
scp $SSH_OPTS $BACKEND_PACKAGE ${SERVER_USER}@${SERVER_HOST}:${REMOTE_BASE_DIR}/backend.tar.gz || handle_error "上传后端文件失败"
scp $SSH_OPTS dist/nginx_cardsys_test.conf ${SERVER_USER}@${SERVER_HOST}:${REMOTE_BASE_DIR}/nginx_cardsys_test.conf || handle_error "上传 Nginx 配置失败"

# 远程执行部署命令
echo "执行远程部署..."
ssh $SSH_OPTS ${SERVER_USER}@${SERVER_HOST} << 'ENDSSH' || handle_error "远程部署失败"
    set -e  # 遇到错误立即退出
    cd /home/pyapp

    echo "解压前端文件..."
    cd www/cardsys_test
    tar xzf ../../frontend.tar.gz
    rm ../../frontend.tar.gz

    echo "解压后端文件..."
    cd ../../workspace/cardsysTest/backend
    tar xzf ../../../backend.tar.gz
    rm ../../../backend.tar.gz

    echo "设置文件权限..."
    chmod +x start_service.sh stop_service.sh

    echo "配置 Conda 环境..."
    source ~/.bashrc
    conda create -n cardsys_test python=3.12 -y
    eval "$(conda shell.bash hook)"
    conda activate cardsys_test
    pip install -r requirements.txt
    pip install gunicorn

    echo "配置 Nginx..."
    cp ../../nginx_cardsys_test.conf ../../nginx/conf/
    rm ../../nginx_cardsys_test.conf

    echo "确保日志目录存在..."
    mkdir -p ../logs

    echo "重启服务..."
    ./stop_service.sh 2>/dev/null || true
    ./start_service.sh &

    echo "重新加载 Nginx 配置..."
    ../../nginx/sbin/nginx -t && ../../nginx/sbin/nginx -s reload

    echo "检查服务状态..."
    ps aux | grep "[g]unicorn" || echo "警告：未检测到 gunicorn 进程"
    curl -s -o /dev/null -w "%{http_code}" localhost:8501 || echo "警告：Nginx 未响应"

    echo "部署完成！"
ENDSSH

echo "=== 部署完成 ==="
echo "请访问 http://${SERVER_HOST}:8501 验证部署" 